<?php
namespace App\Components;
use Cache;
use Carbon\Carbon;
use Log;
/**
 * 工具类
 *
 * @author 郭钊林
 */
class Tools {
  private static $allow_url = [
    '/admin',
    '/admin/update/password'
  ];

    
  /**
   * 生成验证码6位随机数
   */
  public static function getVerCode() {
    return rand(100000, 999999);
  }
    
  /**
   * 将对象或者数组里包含的对象全部转成数组
   * @param $array  array or obj
   * @return array
   */
  public static function objectToArray($array) {
    if(is_object($array)) {
      $array = (array)$array;
    }
    if(is_array($array)) {
      foreach($array as $key => $value) {
        $array[$key] = self::objectToArray($value);
      }
    }
    return $array;
  }
    
  /**
   * 验证手机号码的格式是否正确
   */
  public static function verifyMobile($mobile){
    return preg_match("/^1[3456789]\d{9}$/",$mobile);
  }
    
  /**
   * 验证邮箱的格式是否正确
   */
  public static function verifyEmail($email){
    return preg_match("/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/",$email);
  }
  
  public static function getOrderNumber($user_id = 0){
    return date('YmdHis').$user_id.rand(1000, 9999);
  }

  /**
   * 后台管理员登录密码加密
   * $password  密码
   * $v_password 需要验证的密码
   */
  public static function passwordEncryption($password,$v_password = ''){
    $result = true;
    if(empty($v_password)){
      $result = md5(env('ADMIN_PASSWORD','puppet').md5($password));
    }else{
      (self::passwordEncryption($v_password) != $password) && $result = false;
    }
    return $result;
  }
    
  /**
   * 所有权限数据
   */
  public static function adminLimits($refresh = false){
    $result = Cache::get('adminLimits');
    if(!empty($result)){
      if($refresh){
        Cache::forget('adminLimits');
        self::adminLimits();
      }
      $result = unserialize($result);
    }else{
      $oAdminLimit = new \App\Models\AdminModels\AdminLimit;
      $result = $oAdminLimit->getAllData();
      $expiresAt = Carbon::now()->addDays(7);//缓存7天
      Cache::put('adminLimits', serialize($result),$expiresAt);
    }
    return $result;
  }
  
  /**
   * 所有权限数据
   */
  public static function newAdminLimits($refresh = false){
    $result = Cache::get('newAdminLimits');
    if(!empty($result)){
      if($refresh){
        Cache::forget('newAdminLimits');
        self::newAdminLimits();
      }
      $result = unserialize($result);
    }else{
      $oAdminLimit = new \App\Models\AdminModels\AdminLimit;
      $result = $oAdminLimit->getNewAllData();
      $expiresAt = Carbon::now()->addDays(7);//缓存7天
      Cache::put('newAdminLimits', serialize($result),$expiresAt);
    }
    return $result;
  }
    
  /**
   * 所有角色数据
   */
  public static function adminRoles($refresh = false){
    $result = Cache::get('adminRoles');
    if(!empty($result)){
      if($refresh){
        Cache::forget('adminRoles');
        self::adminRoles();
      }
      $result = unserialize($result);
    }else{
      $oAdminRole = new \App\Models\AdminModels\AdminRole;
      $result = $oAdminRole->getAllData();
      $expiresAt = Carbon::now()->addDays(7);//缓存7天
      Cache::put('adminRoles', serialize($result),$expiresAt);
    }
    return $result;
  }
    
  /**
   * 根据权限limit_ids
   * 获取权限名称数组，或者权限url数组
   */
  public static function getAdminLimitsNameOrUrl($limit_ids,$val = 'limit_name'){
    $adminLimits = self::adminLimits();
    $result = [];
    foreach ($adminLimits as $limit){
      if(in_array($limit['admin_limit_id'], $limit_ids)){
        $result[] = $limit[$val];
      }
    }
    return $result;
  }
    
  /**
   * 验证一个url是否有权限访问
   */
  public static function urlLimit($url,$request){
    $result = false;
    if(!empty($url)){
      $url = preg_replace('/\?(\S+)/', '', $url);//正则替换掉url参数 ?id=...&name=...
      $url = preg_replace('/\/\d{0,}$/','',$url);//正则替换掉/1
      $userLimits = [];
      if($request->session()->has('userLimits')){
        $session_limits = $request->session()->get('userLimits');
        $userLimits = !empty($session_limits) ? $session_limits[0] : [];
      }
      if(in_array($url, self::$allow_url) || in_array($url,$userLimits)){
        $result = true;
      }
    }
    return $result;
  }
    
  /**
   * 获取随机字符串
   * @param type $length 字符串长度
   * @return string 字符串
   */
  public static function getRandChar($length){
    $str = null;
    $strPol = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $max = strlen($strPol)-1;
    for($i=0;$i<$length;$i++){
      $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
    }
    return $str;
  }

  /**
   * 获取随机字符串
   * @param type $length 字符串长度
   * @return string 字符串
   */
  public static function getCardsPwd($length){
    $str = null;
    $strPol = "2356789";
    $max = strlen($strPol)-1;
    for($i=0;$i<$length;$i++){
      $str.=$strPol[rand(0,$max)];
    }
    return $str;
  }

  /**
   * 每四位自动加一个空格
   */
  public static function addBlankSpace($pwd){
    return wordwrap($pwd,4,' ',true);
  }

  public static function token($user_id){
    return md5(time().$user_id. rand(10000, 99999));
  }

  /**
   * 生成token加密串
   */
  public static function crcToken($token){
    $result = sprintf("%u",crc32($token));
    $show = '';
    while($result  >0){
      $s = $result % 62;
      if($s > 35){
        $s=chr($s+61);
      }elseif($s>9 && $s<=35){
        $s=chr($s+55);
      }
      $show .= $s;
      $result = floor($result / 62);
    }
    return $show;
  }
  
  /**
    * 获取微信订单签名
    * @param array $arr 订单数组
    * $key_ Api key
    */
  public static function getWechatSign($arr,$key_){
    ksort($arr);
    $string = '';
    foreach( $arr as $key => $val ){
      $string .= $key . '=' . $val.'&';
    }
    $string .= 'key='.$key_;
    return strtoupper(md5($string));
  }
  
  /**
   * 清除缓存
   */
  public static function cleanWxMsgRecord($openid){
    $key = self::crcToken($openid);
    Cache::forget($key);
    return true;
  }
  
  /**
    * 显示时间
    * $duration秒
    * 将秒转成  时：分：秒
    */
  public static function showTime($duration){
    if(intval($duration) > 0){
      $hour = '';
      $minute = intval($duration/60);
      $second = $duration%60;
      if($minute > 60){
        $hour = intval($minute/60);
        $hour = (strlen($hour) < 2) ? '0'.$hour : $hour;
        $minute = $minute%60;
        $minute = (strlen($minute) < 2) ? '0'.$minute : $minute;
        $second = $duration - intval($hour*3600) - intval($minute*60);
        $second = (strlen($second) < 2) ? '0'.$second : $second;
      }elseif($duration < 60){
        $minute = '00';
        $second = $duration;
        $second = (strlen($second) < 2) ? '0'.$second : $second;
      }else{
        $minute = (strlen($minute) < 2) ? ('0'.$minute) : $minute;
        $second = (strlen($second) < 2) ? '0'.$second : $second;
      }
      return !empty($hour) ? ($hour.':'.$minute.':'.$second) : ($minute.':'.$second);
    }else{
      return 0;
    }
  }
    
  /**
   * 将时：分：秒
   * 转成秒
   */
  public static function turnIntoSeconds($time){
    $result = $time;
    if(strpos($time,':') !== false){
      $time_arr = explode(':',$time);
      if(count($time_arr) == 2){
        $result = $time_arr[0]*60 + $time_arr[1];
      }elseif(count($time_arr) == 3){
        $result = $time_arr[0]*3600 + $time_arr[1]*60 + $time_arr[2];
      }
    }
    return $result;
  }
  
  /**
    * 动态发布时间显示
    */
  public static function showDateTime($create_time){
    $name = '';
    if(date('Y') == date('Y',$create_time)){
      $time = time() - $create_time;
      if($time <= 60){
        $name = '刚刚';
      }elseif($time > 60 && $time <= 3600){
        $name = intval($time/60).'分钟前';
      }elseif($time > 3600 && $time <= 24*60*60){
        $name = intval($time/3600).'小时前';
      }else{
        $name = date('m-d',$create_time);
      }
    }else{
      $name = date('Y-m-d',$create_time);
    }
    return $name;
  }
  
  /**
   * 记录commands脚本日志
   */
  public static function commandsLog($content){
    $log = new \Monolog\Logger('register');
    $path = 'logs/commands-'.date('Y-m-d').'.log';
    $log->pushHandler(new \Monolog\Handler\StreamHandler(storage_path($path), \Monolog\Logger::INFO));
    $log->addInfo(date('Y-m-d H:i:s').':'.$content);
    return true;
  }

	/**
	* 配置读取   二维数组
	*/
	public static function getThird($path){
		$url=str_replace("/public",'',BASE_PATH);
		$data=json_decode(file_get_contents($url.$path),true);
		return $data;
	}
	
	/**
	* 配置写入		二维数组
     * $_SERVER['DOCUMENT_ROOT']获取当前项目的根目录
     * file_put_contents 将一个字符串写入文件
	*/
	public static function setThird($path,$data){
		$url=str_replace("/public",'',$_SERVER['DOCUMENT_ROOT']);
		file_put_contents($url.$path,$data);
		
		//传送配置数据
		$arr=array('path'=>$path,'data'=>json_decode($data,true));
		$curl=$_ENV['VIP_URL']."/admin/config/json";
		self::putData($curl,json_encode($arr));
		$Tcurl=$_ENV['PARNTER_URL']."/admin/config/json";
		self::putData($Tcurl,json_encode($arr));
	}
	/**
	* 读取配置文件的某一个接口的配置   $key="qiniu";
	*/
	public static function getOneArray($path,$key){
		$tvalue=array();
		$data=self::getThird($path);
		if(is_array($data) && isset($data[$key]) ){
			$tvalue=$data[$key];
		}
		return $tvalue;
	}
	/**
	* 读取配置文件的某一个字段值	$keys=array('qiniu','qnAccesskey');
	*/
	public static function getOneconfig($path,$keys){
		$tvalue='';
		$data=self::getThird($path);
		// echo "<pre/>";print_r($data[$keys[0]]);exit();
		if(is_array($data) && isset($data[$keys[0]]) && isset($data[$keys[0]][$keys[1]]) ){
			$tvalue=$data[$keys[0]][$keys[1]];
		}
		return $tvalue;
	}
	//传送配置数据
    //curl_init 初始化数据 curl_setopt设置值 案例如下 curl_close关闭会话
	public static function putData($url,$data){
		$ch = curl_init();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_TIMEOUT,1);
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8"));
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
        $return = curl_exec ( $ch );
        curl_close ( $ch );
	}
	
	//判断用户名是否输入正确  5-11位 字母、数字、下划线 的组合
	static function checkUname($uname){
		if(!preg_match("/^[0-9A-Za-z_]{5,11}$/",$uname)){
			return false;
		}
		return true;
	}
	//判断密码是否正确  6-16位 字母、数字、下划线
	static function checkUpwd($pwd){
		if(!preg_match("/^[0-9A-Za-z_]{6,16}$/",$pwd)){
			return false;
		}
		return true;
	}
	//判断手机号是否正确
	static function checkUmobile($mobile){
		if(!preg_match("/^1[3-9]{1}[0-9]{9}$/",$mobile)){
			return false;
		}
		return true;
	}
	//判断折扣是否正确    100 以内的折扣值
	static function checkDiscountTwo($discount){
		if( (strpos($discount,'.')==1 && preg_match("/^[0-9]{1}\.{1}[0-9]{1}$/",$discount)) || (strpos($discount,'.')==2 && preg_match("/^[1-9]{1}[0-9]{1}\.{1}[0-9]{1}$/",$discount)) || (strpos($discount,'.')==3 && $discount==='100.0') ){
			return true;
		}
		if( !strpos($discount,'.') && (preg_match("/^[0-9]{1}$/",$discount) || preg_match("/^[1-9]{1}[0-9]{1,2}$/",$discount)) && $discount<=100 ){
			return true;
		}
		return false;
	}
	//判断正常的折扣值 10以内
	static function checkDiscount($discount){
		if( strpos($discount,'.')==1 && preg_match("/^[0-9]{1}\.{1}[0-9]{1}$/",$discount) ){
			return true;
		}
		if( !strpos($discount,'.') && preg_match("/^[0-9]{1}$/",$discount) ){
			return true;
		}
		return false;
	}
	//判断是否是网址
	static function checkUrl($url){
		if(preg_match("/^(http|https):\/\/.*$/i",$url)){
			return true;
		}
		return false;
	}
}